﻿
using System;
using System.Collections.Generic;
using Avalonia.Media.Imaging;
using Klear.Library.ViewModels;
using Ursa.Controls;


namespace Klear.Views;

using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;

 
public partial class Dialog : Window
{
    
    public Dialog()
    {
        InitializeComponent();
        
        
#if DEBUG
        this.AttachDevTools();
#endif
    }
 
    private void InitializeComponent()
    {
        
        AvaloniaXamlLoader.Load(this);
    }
 
    private void Close_OnClick(object? sender, RoutedEventArgs e)
    {
        Close();
    }

    
    private void Confirm(object? sender, RoutedEventArgs routedEventArgs)
    {
        IncomeExpensesViewModel viewModel = DataContext as IncomeExpensesViewModel;
        if (viewModel != null)
        {
            viewModel.AddIncomeExpense();
        }
        
        Close();
    }

    private async void UploadImg(object? sender, RoutedEventArgs e)
    {
        // 确保 UploadedImage 被正确初始化
        UploadedImage = this.FindControl<Image>("UploadedImage");

        if (UploadedImage == null)
        {
            Console.WriteLine("无法找到 UploadedImage 控件，请检查 XAML 中的控件名称。");
            return;
        }

        // 文件选择对话框代码
        var openFileDialog = new OpenFileDialog
        {
            Title = "选择图片",
            AllowMultiple = false,
            Filters = new List<FileDialogFilter>
            {
                new FileDialogFilter
                {
                    Name = "图片文件",
                    Extensions = new List<string> { "jpg", "jpeg", "png", "gif", "bmp" }
                }
            }
        };

        // 异步等待文件选择
        var result = await openFileDialog.ShowAsync(this);

        if (result != null && result.Length > 0)
        {
            try
            {
                string selectedFilePath = result[0];
                var image = new Bitmap(selectedFilePath);
                UploadedImage.Source = image;
                
                string updatedPath = selectedFilePath.Replace("\\", "\\\\");
                
                Console.WriteLine(updatedPath);
                IncomeExpensesViewModel viewModel = DataContext as IncomeExpensesViewModel;
                if (viewModel != null)
                {
                    viewModel.UploadIncomeExpenseByAiAsync(updatedPath);
                    viewModel.IsLoading = "正在解析中,请稍后...";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("加载图片失败: " + ex.Message);
            }
        }
    }



}